import { defineStore } from 'pinia'
import { storage } from '@/utils/storage'
import { getUserInfo, login } from '@/api/auth'
import router from '@/router'
import { ElNotification } from 'element-plus'

export const TOKEN = 'token'
export const USER_INFO = 'userInfo'
interface IUserState {
  token: string | null
  userInfo: {
    username: string
    role: string
  }
  permission: string[]
}

export const useUserInfoStore = defineStore({
  id: 'user',
  state: (): IUserState => ({
    token: storage.get(TOKEN),
    userInfo: storage.get(USER_INFO) || { username: '', role: '' },
    permission: []
  }),
  getters: {
    isLogin(state) {
      return Boolean(state.token)
    }
  },
  actions: {
    resetUser() {},
    setToken(token: string) {
      this.token = token
      storage.set(TOKEN, token)
    },
    setPermission(permission: string[]) {
      this.permission = permission
    },
    async setUser() {
      const { data } = await getUserInfo()
      if (data?.permission?.length) {
        this.setPermission(data.permission)
      }
      this.userInfo = data
      storage.set(USER_INFO, data)
    },
    async login(params: any) {
      const { data } = await login(params)
      this.setToken(data.token)
      router.push((router.currentRoute.value.query?.redirect || '/') as string)
      await this.setUser()
      ElNotification({
        title: '登录成功，小东西',
        type: 'success',
        message: `欢迎回来， ${this.userInfo.username}兄弟`
      })
    }
  }
})
